package com.butterfly.hotkey.worker.framework.netty.dashboard;

import com.butterfly.hotkey.core.constant.Constants;
import com.butterfly.hotkey.core.constant.MsgTypeConst;
import com.butterfly.hotkey.core.model.msg.HotKeyMsg;
import com.butterfly.hotkey.core.util.FastJsonUtil;
import com.butterfly.hotkey.core.util.NettyMsgUtil;
import com.butterfly.hotkey.worker.framework.component.WorkerContainer;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author butterfly
 */
@ChannelHandler.Sharable
public class NettyClientHandler extends SimpleChannelInboundHandler<String> {

    private static final Logger log = LoggerFactory.getLogger(Constants.WORKER);

    private final WorkerContainer workerContainer;

    public NettyClientHandler(WorkerContainer workerContainer) {
        this.workerContainer = workerContainer;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if (idleStateEvent.state() == IdleState.ALL_IDLE) {
                //向服务端发送消息
                ctx.writeAndFlush(NettyMsgUtil.buildByteBuf(new HotKeyMsg(MsgTypeConst.PING)));
            }
        }

        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("channelActive:{}", ctx.name());
        workerContainer.addDashboard(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

        // dashboard断连，等待之后继续重试
        workerContainer.disconnectDashboard(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String message) {
        HotKeyMsg msg = FastJsonUtil.parseObject(message, HotKeyMsg.class);
        if (MsgTypeConst.PONG == msg.getMsgType()) {
            log.info("heart beat");
        }
    }

}
